# !/usr/bin/env python
# -*- coding:utf-8 -*-
import logging
from datetime import datetime

# 导入PyQt6
from PyQt6.QtCore import Qt, QTimer, pyqtSignal
from PyQt6.QtWidgets import  QDialog

from view import tc_sql
from view.add import Ui_yongli
from service.tishi_service import Tishi

    # ==============================================================================
    # view 7.用例信息
    # ==============================================================================


class AddCase(QDialog, Ui_yongli):
    """用例信息页面"""
    confirmed_signal_addcase = pyqtSignal()

    def __init__(self, case_db, mkname=None, mkid=None, value=None):
        super().__init__()
        self.setupUi(self)
        self.case_db = case_db
        self.case_db.connect()  # 创建游标
        self.ts = Tishi()  # 提示框
        self.save_flag = 0  # 保存成功标识：1

        self.mkid = mkid
        if mkname or self.mkid:
            self.mk.addItem(mkname + '—ID:' + str(mkid))

        self.mk.lineEdit().returnPressed.connect(self.mkcx_add)  # 编辑，触发模块查询
        self.mk.lineEdit().textEdited.connect(self.text_changed)
        self.mk.lineEdit().setCompleter(None)  # 关闭自动补全功能
        self.timer = QTimer()

        self.baocun.setAutoDefault(False)  # 取消回车激活按钮
        self.baocun_2.setAutoDefault(False)
        self.quxiao.setAutoDefault(False)

        self.value = value
        if self.value:  # 编辑时，传入value
            fields = [self.biaoti, self.qianzhi, self.buzou,
                      self.jieguo, self.beizhu, self.guanjc]
            for i in range(6):
                fields[i].setText(self.value[i])  # 设置文本框内容

            index = self.youxianji.findText(self.value[6], Qt.MatchFlag.MatchFixedString)
            self.youxianji.setCurrentIndex(index)  # 设置下拉框内容
            index2 = self.leixing.findText(self.value[7], Qt.MatchFlag.MatchFixedString)
            self.leixing.setCurrentIndex(index2)

    def text_changed(self):
        # 取消之前可能存在的计时器
        if self.timer:
            self.timer.stop()
            self.timer.deleteLater()
        # 创建一个新的计时器，在3秒后触发查询函数
        self.timer = QTimer(self)
        self.timer.setSingleShot(True)  # 设置为单次触发
        self.timer.timeout.connect(self.mkcx_add)
        self.timer.start(3000)  # 3秒后触发

    def mkcx_add(self):
        """用例页面，模块查询"""
        if self.timer and self.timer.isActive():  # 关闭并删除计时器（确保不会触发3秒的定时事件）
            self.timer.stop()
            self.timer.deleteLater()
            self.timer = None  # 清空计时器引用

        value = ['%' + self.mk.lineEdit().text() + '%']  # 获取输入文本
        row = self.case_db.query_many(
            "select modulename,moduleid from module where modulename like ? and status = 10", value)
        row.reverse()
        self.mk.clear()  # 清空下拉框
        if row:
            for result in row:  # 将模块名称、ID，写入下拉框选项
                self.mk.addItem(result[0] + '—ID:' + str(result[1]))
        else:
            self.mkid = 0
        logging.info('用例页面，模块查询')

    def save_value(self):
        """用例，保存操作"""

        current_time = datetime.now()
        formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
        self.baocun.setEnabled(False)  # 保存按钮置灰

        parts = self.mk.currentText().split("—ID:")
        if len(parts) == 2:
            self.mkid = parts[1]
        else:
            self.mkid = 0

        if not self.biaoti.text() or self.mkid == 0 or self.buzou.toPlainText() == "1.":
            self.ts.xinxi("标题、模块或步骤不能为空！")
            self.baocun.setEnabled(True)  # 保存按钮恢复
            return

        tc_types = tc_sql.codes_dict['tc_types'].get(self.leixing.currentText(), '') if self.leixing.currentText() else ''
        priority = tc_sql.codes_dict['priority'].get(self.youxianji.currentText(), '') if self.youxianji.currentText() else ''
        status = tc_sql.codes_dict['status'].get(self.zhuagntai.currentText(), '') if self.zhuagntai.currentText() else ''
        if self.value:  # 编辑
            sql = f"update testcase set moduleid=? , title=? , preconditions=? , step=? , expect=? , keyword=? ," \
                  f" priority=? , types=? , status=? ,modificationdate=? ,remarks = ?  where caseid=?"
            value = (self.mkid, self.biaoti.text(), self.qianzhi.toPlainText(),
                    self.buzou.toPlainText(), self.jieguo.toPlainText(),
                    self.guanjc.text(), priority, tc_types, status,
                    formatted_time, self.beizhu.text(), self.value[8])
            self.savesql_yongli(sql, value)
        else:  # 新增
            value = (self.mkid, self.biaoti.text(), self.qianzhi.toPlainText(),
                    self.buzou.toPlainText(), self.jieguo.toPlainText(),
                    self.guanjc.text(), priority, tc_types, status,
                    formatted_time, '', self.beizhu.text())
            self.savesql_yongli('INSERT INTO testcase VALUES (NULL,?,?,?,?,?,?,?,?,?,?,?,?)', value)

    def save_next(self):
        """新增下一条，清空页面"""
        self.save_value()
        if self.save_flag == 1:
            self.baocun.setEnabled(True)  # 保存按钮恢复
            # self.biaoti.clear()     # 清空输入框
            self.qianzhi.clear()
            self.buzou.setText("1.")
            self.jieguo.setText("1.")
            self.beizhu.clear()
            # self.youxianji.setCurrentIndex(0)
            # self.leixing.setCurrentIndex(0)
            # self.zhuagntai.setCurrentIndex(0)
            self.value = None  # 清空编辑数据，避免走入编辑流程
        logging.info('保存用例，清空页面')

    def save(self):
        """保存，关闭窗口"""
        self.save_value()
        if self.save_flag == 1:
            self.close()  # 关闭保存窗口

        logging.info('保存用例，关闭窗口')

    @tc_sql.timeshow
    def savesql_yongli(self, sql, value):
        """用例保存sql"""
        if self.case_db.operate_one(sql, value):
            self.mkid = 0
            self.save_flag = 1
        else:
            self.ts.xinxi("保存失败，请检查")
            self.baocun.setEnabled(True)  # 保存按钮恢复

    def closeEvent(self, QCloseEvent):
        """窗口关闭时关闭数据库"""
        self.case_db.over()  # 关闭游标
        if self.save_flag == 1:
            self.confirmed_signal_addcase.emit()  # 发射查询信号
        # self.case_db.conn.close()
        logging.info("[用例信息页面，游标关闭]")
